﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using log4net.Appender;
using log4net.Layout;
using log4net.Config;
using log4net;
using System.Reflection;

namespace Laugh.Logging
{
    internal static class LogCfg
    {
        private static string cfgPath = AppDomain.CurrentDomain.BaseDirectory + "bin";

        public static void Init()
        {
            FileInfo file = new FileInfo(Path.Combine(cfgPath, "log4net.config"));
            if (file.Exists)
            {
                XmlConfigurator.ConfigureAndWatch(file);
                return;
            }

            var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Laugh.Logging.log4net.Config");
            if (stream != null)
            {
                XmlConfigurator.Configure(stream);
                return;
            }

            LogByFile();
        }

        public static void LogByFile()
        {
            string txtLogPath = string.Empty;

            txtLogPath = Path.Combine(cfgPath, "ErrorLog.txt");

            FileAppender fileAppender = new FileAppender();
            fileAppender.Name = "LogFileAppender";
            fileAppender.File = txtLogPath;
            fileAppender.AppendToFile = true;

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "记录时间：%date 线程ID:[%thread] 日志级别：%-5level 出错类：%logger property:[%property{NDC}] - 错误描述：%message%newline";
            patternLayout.ActivateOptions();
            fileAppender.Layout = patternLayout;

            //选择UTF8编码，确保中文不乱码。
            fileAppender.Encoding = Encoding.UTF8;

            fileAppender.ActivateOptions();

            BasicConfigurator.Configure(fileAppender);
        }
    }
}
